package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink05_Transform_Map {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        //2.从端口中获取数据
//        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
//        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");
        DataStreamSource<String> streamSource = env.fromElements("s1,1,1", "s2,2,2", "s3,3,3");

        //TODO 3.将从端口读取到的字符串转为WaterSensor
//        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
//            @Override
//            public WaterSensor map(String value) throws Exception {
//                String[] split = value.split(",");
//                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
//            }
//        });
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MyMap());


        map.print();

        env.execute();
    }

    //TODO 富函数
    public static class MyMap extends RichMapFunction<String,WaterSensor>{
        /**
         * 声明周期方法，最先被调用，每个并行度调用一次
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open....");
        }

        /**
         * 声明周期方法，最后被调用，每个并行度调用一次,在读文件时每个并行度调用两次
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close....");
        }

        @Override
        public WaterSensor map(String value) throws Exception {
//            System.out.println("jobId:"+getRuntimeContext().getJobId());
//            System.out.println("TaskName:"+getRuntimeContext().getTaskName());

            String[] split = value.split(",");
            return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
        }


    }
}
